package com.yanqu.road.sync.message;

import com.google.protobuf.ByteString;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.syncMessage.SyncMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

public class Caller {

    private final Dispatcher dispatcher = new Dispatcher();

    public ResultProcessor sendMsgSync(long rawServerId, long forwardServerId, long userId, int code, int sCode, int activityId, GeneratedMessage.Builder<?> requestBuilder, GeneratedMessage.Builder<?> responseBuilder) {
        SyncMessage.Request.Builder builder = SyncMessage.Request.newBuilder();
        builder.setCmdCode(code);
        if (requestBuilder != null) {
            ByteString byteString = requestBuilder.build().toByteString();
            builder.setDataBytes(byteString);
        }
        builder.setActivityId(activityId);
        builder.setRawServerId(rawServerId);
        builder.setForwardServerId(forwardServerId);
        builder.setSenderId(userId);
        ResultProcessor resultProcessor = this.dispatcher.pending(builder);
        resultProcessor.setResponseBuilder(responseBuilder);
        YanQuMessage buildMessage = YanQuMessageUtils.buildMessage(sCode, 0, builder);
        resultProcessor.setRequest(buildMessage);
        return resultProcessor;
    }


    public void receiveMsgHandler(YanQuMessage packet) {
        try {
            SyncMessage.Response response = SyncMessage.Response.parseFrom(packet.getBytes());
            this.dispatcher.receive(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

    }

    public void scheduleClean() {
        this.dispatcher.scheduleCleanResultProcessor();
    }
}
